package com.smart.netty;

import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {
	
	private final int port;

	public EchoServer(int port){
		this.port=port;
	}

	// 启动服务器
	public void start() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).localAddress(new InetSocketAddress(port))
				.childOption(ChannelOption.SO_KEEPALIVE, true) // 2小时没有信息流则开启
				.option(ChannelOption.SO_BACKLOG,1024).channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new ReadTimeoutHandler(5));
						//5秒没有读事件就关掉
						ch.pipeline().addLast(new MyDecoder()); // 自定义的解码
						ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
						ch.pipeline().addLast(new TcpHandler());
					}
				});
			ChannelFuture f = b.bind().sync();
			f.channel().closeFuture().sync();
		}finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}
}